<template>
	<view class="leancloud-demo">
		<u-toast ref="uToast" />
		
		<view class="section">
			<view class="section-title">LeanCloud 操作示例</view>
			
			<!-- 用户操作 -->
			<view class="operation-group">
				<view class="group-title">用户操作</view>
				<view class="input-group">
					<input type="text" v-model="user.username" placeholder="用户名" />
					<input type="password" v-model="user.password" placeholder="密码" />
				</view>
				<view class="btn-group">
					<u-button type="primary" @click="handleUserSignUp">注册用户</u-button>
					<u-button type="primary" @click="handleUserLogin">用户登录</u-button>
					<u-button type="warning" @click="handleUserLogout">用户登出</u-button>
					<u-button type="info" @click="handleGetCurrentUser">获取当前用户</u-button>
				</view>
				<view class="tips" v-if="currentUser">
					<text>当前用户: {{currentUser.username}}</text>
				</view>
			</view>
			
			<!-- 对象操作 -->
			<view class="operation-group">
				<view class="group-title">对象操作</view>
				<view class="input-group">
					<input type="text" v-model="objectData.className" placeholder="数据表名称" />
					<input type="text" v-model="objectData.name" placeholder="名称" />
					<input type="text" v-model="objectData.description" placeholder="描述" />
				</view>
				<view class="btn-group">
					<u-button type="primary" @click="handleCreateObject">创建对象</u-button>
					<u-button type="primary" @click="handleQueryObjects">查询对象</u-button>
					<u-button type="primary" @click="handleUpdateObject" :disabled="!selectedObjectId">更新对象</u-button>
					<u-button type="error" @click="handleDeleteObject" :disabled="!selectedObjectId">删除对象</u-button>
				</view>
			</view>
			
			<!-- 查询结果列表 -->
			<view class="result-list" v-if="queryResults.length > 0">
				<view class="result-title">查询结果：</view>
				<view class="result-item" v-for="(item, index) in queryResults" :key="index" @click="selectObject(item)">
					<view :class="['item-content', {'selected': selectedObjectId === item.objectId}]">
						<text class="item-id">ID: {{item.objectId}}</text>
						<text class="item-name">名称: {{item.name}}</text>
						<text class="item-desc">描述: {{item.description}}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 操作日志 -->
		<view class="operation-log">
			<view class="log-title">操作日志</view>
			<scroll-view scroll-y class="log-content">
				<view class="log-item" v-for="(log, index) in logs" :key="index">
					<text class="log-time">{{log.time}}</text>
					<text class="log-message">{{log.message}}</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			user: {
				username: '',
				password: ''
			},
			currentUser: null,
			objectData: {
				className: 'TestData',
				name: '',
				description: ''
			},
			queryResults: [],
			selectedObjectId: '',
			logs: []
		}
	},
	onLoad() {
		// 检查当前是否有用户登录
		this.getCurrentUserInfo();
		this.addLog('页面加载完成');
	},
	methods: {
		// 日志管理
		addLog(message) {
			const now = new Date();
			const timeStr = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
			this.logs.unshift({
				time: timeStr,
				message: message
			});
			// 最多保留50条日志
			if (this.logs.length > 50) {
				this.logs.pop();
			}
		},
		
		// 显示消息
		showMessage(message, type = 'success') {
			this.$refs.uToast.show({
				title: message,
				type: type
			});
			this.addLog(message);
		},
		
		// 获取当前用户信息
		async getCurrentUserInfo() {
			try {
				const user = await this.$leanCloud.user.getCurrent();
				this.currentUser = user;
				if (user) {
					this.addLog(`当前登录用户: ${user.username}`);
				} else {
					this.addLog('当前未登录');
				}
			} catch (error) {
				this.addLog(`获取当前用户失败: ${error.message || '未知错误'}`);
			}
		},
		
		// 用户操作
		async handleUserSignUp() {
			if (!this.user.username || !this.user.password) {
				this.showMessage('用户名和密码不能为空', 'warning');
				return;
			}
			
			try {
				const result = await this.$leanCloud.user.signUp(this.user.username, this.user.password);
				this.showMessage('用户注册成功');
				this.currentUser = result;
			} catch (error) {
				this.showMessage(`注册失败: ${error.message || '未知错误'}`, 'error');
			}
		},
		
		async handleUserLogin() {
			if (!this.user.username || !this.user.password) {
				this.showMessage('用户名和密码不能为空', 'warning');
				return;
			}
			
			try {
				const result = await this.$leanCloud.user.login(this.user.username, this.user.password);
				this.showMessage('登录成功');
				this.currentUser = result;
			} catch (error) {
				this.showMessage(`登录失败: ${error.message || '未知错误'}`, 'error');
			}
		},
		
		async handleUserLogout() {
			try {
				await this.$leanCloud.user.logout();
				this.showMessage('登出成功');
				this.currentUser = null;
			} catch (error) {
				this.showMessage(`登出失败: ${error.message || '未知错误'}`, 'error');
			}
		},
		
		async handleGetCurrentUser() {
			await this.getCurrentUserInfo();
			if (this.currentUser) {
				this.showMessage(`当前用户: ${this.currentUser.username}`);
			} else {
				this.showMessage('当前未登录', 'info');
			}
		},
		
		// 对象操作
		async handleCreateObject() {
			if (!this.objectData.className || !this.objectData.name) {
				this.showMessage('类名和名称不能为空', 'warning');
				return;
			}
			
			try {
				const data = {
					name: this.objectData.name,
					description: this.objectData.description || ''
				};
				
				const result = await this.$leanCloud.create(this.objectData.className, data);
				this.showMessage('创建对象成功');
				this.addLog(`创建对象成功，ID: ${result.objectId}`);
				
				// 创建后自动查询
				this.handleQueryObjects();
			} catch (error) {
				this.showMessage(`创建对象失败: ${error.message || '未知错误'}`, 'error');
			}
		},
		
		async handleQueryObjects() {
			if (!this.objectData.className) {
				this.showMessage('类名不能为空', 'warning');
				return;
			}
			
			try {
				const result = await this.$leanCloud.query(this.objectData.className);
				this.queryResults = result.results || [];
				this.showMessage(`查询成功，共 ${this.queryResults.length} 条数据`);
			} catch (error) {
				this.showMessage(`查询失败: ${error.message || '未知错误'}`, 'error');
			}
		},
		
		selectObject(item) {
			this.selectedObjectId = item.objectId;
			this.objectData.name = item.name;
			this.objectData.description = item.description || '';
			this.addLog(`选择对象: ${item.objectId}`);
		},
		
		async handleUpdateObject() {
			if (!this.selectedObjectId) {
				this.showMessage('请先选择一个对象', 'warning');
				return;
			}
			
			try {
				const data = {
					name: this.objectData.name,
					description: this.objectData.description || ''
				};
				
				await this.$leanCloud.update(this.objectData.className, this.selectedObjectId, data);
				this.showMessage('更新对象成功');
				
				// 更新后自动查询
				this.handleQueryObjects();
			} catch (error) {
				this.showMessage(`更新对象失败: ${error.message || '未知错误'}`, 'error');
			}
		},
		
		async handleDeleteObject() {
			if (!this.selectedObjectId) {
				this.showMessage('请先选择一个对象', 'warning');
				return;
			}
			
			try {
				await this.$leanCloud.delete(this.objectData.className, this.selectedObjectId);
				this.showMessage('删除对象成功');
				this.selectedObjectId = '';
				this.objectData.name = '';
				this.objectData.description = '';
				
				// 删除后自动查询
				this.handleQueryObjects();
			} catch (error) {
				this.showMessage(`删除对象失败: ${error.message || '未知错误'}`, 'error');
			}
		}
	}
}
</script>

<style lang="scss">
.leancloud-demo {
	padding: 20rpx;
	
	.section {
		margin-bottom: 30rpx;
		
		.section-title {
			font-size: 36rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
			text-align: center;
		}
	}
	
	.operation-group {
		background-color: #f8f8f8;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
		
		.group-title {
			font-size: 30rpx;
			font-weight: bold;
			margin-bottom: 15rpx;
		}
		
		.input-group {
			margin-bottom: 15rpx;
			
			input {
				background-color: #fff;
				height: 70rpx;
				border-radius: 8rpx;
				padding: 0 15rpx;
				margin-bottom: 10rpx;
			}
		}
		
		.btn-group {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			
			.u-button {
				margin-bottom: 10rpx;
				margin-right: 10rpx;
				flex: 0 0 48%;
			}
		}
		
		.tips {
			margin-top: 10rpx;
			color: #666;
			font-size: 26rpx;
		}
	}
	
	.result-list {
		margin-top: 20rpx;
		
		.result-title {
			font-size: 28rpx;
			font-weight: bold;
			margin-bottom: 10rpx;
		}
		
		.result-item {
			margin-bottom: 10rpx;
			
			.item-content {
				background-color: #f0f0f0;
				padding: 15rpx;
				border-radius: 8rpx;
				display: flex;
				flex-direction: column;
				
				&.selected {
					background-color: #e1f3ff;
					border: 1px solid #007aff;
				}
				
				.item-id {
					font-size: 24rpx;
					color: #999;
				}
				
				.item-name {
					font-size: 28rpx;
					font-weight: bold;
				}
				
				.item-desc {
					font-size: 26rpx;
					color: #666;
				}
			}
		}
	}
	
	.operation-log {
		margin-top: 30rpx;
		
		.log-title {
			font-size: 28rpx;
			font-weight: bold;
			margin-bottom: 10rpx;
		}
		
		.log-content {
			height: 300rpx;
			background-color: #f5f5f5;
			padding: 10rpx;
			border-radius: 8rpx;
			
			.log-item {
				font-size: 24rpx;
				margin-bottom: 8rpx;
				
				.log-time {
					color: #007aff;
					margin-right: 10rpx;
				}
				
				.log-message {
					color: #333;
				}
			}
		}
	}
}
</style>